package com.hoo.service.account;

import com.hoo.entity.account.Resource;
import com.hoo.mapper.account.ResourceMapper;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionService {
	  @Autowired
	  ResourceMapper resourceMapper;
	  /**
	   * 缓存权限菜单树 key 为权限id，value为id对应的菜单列表
	   */
	  private final Map<Integer, List<Resource>> roleMenuMapCache =
	      new HashMap<Integer, List<Resource>>();

	  /**
	   * 维护权限菜单对应的更新时间，只要缓存更新则修改默认更新时间
	   */
	  private final Map<Integer, Long> roleMenuRefreshMap = new HashMap<Integer, Long>();

	  /**
	   * 所有菜单的缓存Map, key为菜单的url，value为菜单对象
	   */
	  private final Map<String, Resource> menuMapCache = new HashMap<String, Resource>();

	  //
	  public List<Resource> getResourcesByRoleId(Integer roleId) {
	    return resourceMapper.getResourcesByRoleId(roleId);
	  }


	  private List<Resource> getMenusByParentIdAndRoleId(Integer parentId, Integer roleId) {
	    //
	    List<Resource> menus = resourceMapper.getMenusByParenIdAndRoleId(parentId, roleId);

	    if (CollectionUtils.isNotEmpty(menus)) {
	      for (Resource menu : menus) {
	        List<Resource> tmpMenus = getMenusByParentIdAndRoleId(menu.getId(), roleId);
	        if (CollectionUtils.isNotEmpty(tmpMenus)) {
	          menu.setChildren(tmpMenus);
	        }
	      }
	    }

	    return menus;
	  }

	  /**
	   * 根据权限id查询菜单树， 如果缓存中存在该权限菜单则从缓存中获取，否则读取数据库并保持到缓存中
	   * 
	   * @param roleId 权限id
	   * @param force 是否强制从数据库读取
	   * @return
	   */
	  public List<Resource> getMenusByRoleId(Integer roleId, Integer moduleId, boolean force) {
	    List<Resource> menus = null;
	    if (force) {
	      menus = getMenusByParentIdAndRoleId(moduleId, roleId);
	      roleMenuMapCache.put(roleId, menus);
	    } else {
	      menus = roleMenuMapCache.get(roleId);
	      if (menus == null) {
	        menus = getMenusByParentIdAndRoleId(moduleId, roleId);
	        if (menus != null) {
	          // 把权限对应菜单放入缓存
	          roleMenuMapCache.put(roleId, menus);
	          // 同事更新权限缓存更新时间
	          roleMenuRefreshMap.put(roleId, System.currentTimeMillis());
	        }
	      }
	    }
	    return menus;
	  }

	  /**
	   * 根据url查找当前所属模块id
	   * 
	   * @param path
	   * @return
	   */
	  public Resource getResourceBelongsFromUrl(Integer roleId, String path) {
	    // 改成正则匹配更好
	    List<Resource> resources = getResourcesByRoleId(roleId);
	    for (Resource resource : resources) {
	      if (Resource.TYPE_MENU == resource.getResourceType() && path.startsWith(resource.getHref())) {
	        return resource;
	      }
	    }
	    return null;
	  }
}
